<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HOC</title>
</head>

<body>
  <script src="../../node_modules/vue/dist/vue.js"></script>
  <div id="app">
    <smart-avatar username='vuejs'></smart-avatar>
  </div>
  <script>
    // base Component
    const Avatar = {
      props: ['src'],
      template: `<img :src="src" alt="avatar"/>`
    }

    // mockAPI
    function fetchURL(username, cb) {
      setTimeout(() => {
        // hard coded, bonus: exercise: make it fetch from gravatar!
        cb('https://avatars3.githubusercontent.com/u/6128107?v=4&s=200')
      }, 500)
    }

    // implement this
    function withAvatarURL(InnerComponent) {
      // 可以缓存数据，防止重复的API请求
      return {
        props: ['username'],
        data() {
          return {
            url: "",
          }
        },
        created() {
          fetchURL(this.username, url => this.url = url)
        },
        render(h) {
          return h(InnerComponent, {
            props: {
              src: this.url || "http://via.placeholder.com/200x200"
            }
          })
        }
      }
    }
    const SmartAvatar = withAvatarURL(Avatar);
    new Vue({
      el: '#app',
      components: { SmartAvatar }
    })
  </script>
</body>

</html>